const app = getApp();

Page({
  data: {
    id: null,
    leaveInfo: null,
    isLoading: true,
    error: false,
    errorMsg: ''
  },

  onLoad: function(options) {
    if (options.id) {
      this.setData({
        id: options.id
      });
      this.fetchLeaveDetail(options.id);
    } else {
      this.setData({
        error: true,
        errorMsg: '未找到请假记录ID',
        isLoading: false
      });
    }
  },

  // 获取请假详情
  fetchLeaveDetail: function(id) {
    this.setData({ isLoading: true, error: false });
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/admin/leaves/${id}`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 处理状态文本
          let statusText = '';
          let statusClass = '';
          
          switch(res.data.status) {
            case 'pending':
              statusText = '待审批';
              statusClass = 'pending';
              break;
            case 'approved':
              statusText = '已批准';
              statusClass = 'approved';
              break;
            case 'rejected':
              statusText = '已拒绝';
              statusClass = 'rejected';
              break;
          }
          
          // 处理附件数据
          let attachments = [];
          if (res.data.attachments) {
            // 直接处理字符串路径
            if (typeof res.data.attachments === 'string') {
              const fileUrl = res.data.attachments;
              const fileName = fileUrl.split('/').pop();
              const fileExt = fileName.split('.').pop().toLowerCase();
              
              attachments = [{
                url: `${app.globalData.serverUrl}${fileUrl}`,
                name: fileName,
                isPdf: fileExt === 'pdf',
                isImage: ['jpg', 'jpeg', 'png', 'gif'].includes(fileExt),
                fileType: fileExt.toUpperCase()
              }];
            } else if (Array.isArray(res.data.attachments)) {
              // 如果已经是数组，直接处理
              attachments = res.data.attachments.map(item => {
                const fileUrl = item.url || item;
                const fileName = fileUrl.split('/').pop();
                const fileExt = fileName.split('.').pop().toLowerCase();
                
                return {
                  url: fileUrl.startsWith('http') ? fileUrl : `${app.globalData.serverUrl}${fileUrl}`,
                  name: item.name || fileName,
                  isPdf: fileExt === 'pdf',
                  isImage: ['jpg', 'jpeg', 'png', 'gif'].includes(fileExt),
                  fileType: fileExt.toUpperCase()
                };
              });
            }
          }
          
          // 格式化时间
          const formatDate = (dateStr) => {
            if (!dateStr) return '';
            const date = new Date(dateStr);
            return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
          };
          
          this.setData({
            leaveInfo: {
              ...res.data,
              statusText,
              status: statusClass,
              attachments,
              // 格式化各种时间
              formattedStartDate: formatDate(res.data.startDate),
              formattedEndDate: formatDate(res.data.endDate),
              formattedApplyTime: formatDate(res.data.applyTime),
              formattedApproveTime: formatDate(res.data.approveTime)
            },
            isLoading: false
          });
        } else {
          this.setData({
            error: true,
            errorMsg: res.data.message || '获取请假详情失败',
            isLoading: false
          });
        }
      },
      fail: (err) => {
        this.setData({
          error: true,
          errorMsg: '网络错误，请重试',
          isLoading: false
        });
      }
    });
  },

  // 批准请假
  approveLeave: function() {
    wx.showModal({
      title: '确认批准',
      content: '确定批准该请假申请吗？',
      success: (res) => {
        if (res.confirm) {
          this.updateLeaveStatus('approved');
        }
      }
    });
  },

  // 拒绝请假
  rejectLeave: function() {
    wx.showModal({
      title: '拒绝原因',
      editable: true,
      placeholderText: '请输入拒绝原因',
      success: (res) => {
        if (res.confirm && res.content) {
          this.updateLeaveStatus('rejected', res.content);
        }
      }
    });
  },

  // 更新请假状态
  updateLeaveStatus: function(status, reason = '') {
    wx.showLoading({
      title: '处理中...'
    });
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/admin/leaves/${this.data.id}/status`,
      method: 'PUT',
      data: {
        status,
        reason
      },
      header: {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          wx.showToast({
            title: status === 'approved' ? '已批准' : '已拒绝',
            icon: 'success'
          });
          
          // 刷新详情
          this.fetchLeaveDetail(this.data.id);
          
          // 设置上一页需要刷新
          const pages = getCurrentPages();
          if (pages.length > 1) {
            const prevPage = pages[pages.length - 2];
            prevPage.setData({
              needRefresh: true
            });
          }
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 预览图片
  previewImage: function(e) {
    const url = e.currentTarget.dataset.url;
    if (!url) return;
    
    wx.previewImage({
      urls: [url],
      current: url
    });
  },
  
  // 预览文件
  previewFile: function(e) {
    const url = e.currentTarget.dataset.url;
    if (!url) return;
    
    wx.showLoading({
      title: '打开文件中...',
    });
    
    // 下载文件
    wx.downloadFile({
      url: url,
      success: function(res) {
        wx.hideLoading();
        // 打开文件
        wx.openDocument({
          filePath: res.tempFilePath,
          success: function() {
            console.log('打开文档成功');
          },
          fail: function(error) {
            console.error('打开文档失败:', error);
            wx.showToast({
              title: '无法打开文件',
              icon: 'none'
            });
          }
        });
      },
      fail: function(error) {
        wx.hideLoading();
        console.error('下载文件失败:', error);
        wx.showToast({
          title: '下载文件失败',
          icon: 'none'
        });
      }
    });
  }
});